
import { getRoomDomain } from "../global/map";
import { jobGoto } from "./goto";

export const jobRepair = {
    /**
     * 
     * @param {RoomObject} structure 
     */
    filter(structure){
        if(!(structure instanceof Structure)){
            return false;
        }

        let isMine = structure.my || 
            [STRUCTURE_WALL,STRUCTURE_CONTAINER,STRUCTURE_ROAD]
                .some((type)=>type === structure.structureType);
        let isDamaged = structure.hits<structure.hitsMax;
        return isMine && isDamaged;
    },
    /**
     * 
     * @param {String[]|Room[]} rooms 
     */
    findTargets(rooms){
        if(rooms.length === 0){
            return [];
        }
        let isName = rooms[0] instanceof String;
        let targets = [];
        for(let room of rooms){
            if(isName){
                room = Game.rooms[room];
                if(!room){
                    continue;
                }
            }

            targets.push(...room.find(FIND_STRUCTURES,{filter: this.filter}));
        }
    },
    getTargets(room){
        if(room.__repairTargets !== undefined){
            return room.__repairTargets;
        }
        return room.__repairTargets = this.findTargets(getRoomDomain(room));
    },
    /**
     * 
     * @param {AnyCreep} creep 
     * @param {AnyOwnedStructure[]} structures
     */
    run(creep, structures = undefined){
        if(structures === undefined){
            let room = Game.rooms[creep.room.memory.mainRoomName];
            if(!room){
                return ERR_INVALID_ARGS;
            }
            structures = this.getTargets(room);
        }

        if(structures.length === 0){
            return ERR_INVALID_ARGS;
        }

        structures = jobGoto.sortTargetsByDistance(creep, structures);

        let ret;
        for(let target of structures){
            ret = creep.repair(target);
            if(ret === OK || ret === ERR_NOT_IN_RANGE){
                break;
            }
        }
        if(ret === ERR_NOT_IN_RANGE){
            ret = OK;
            jobGoto.run(creep, structures, {visualizePathStyle:{stroke:"#aaff00"}});
        }
        return ret;
    }
}